package cn.itcast.email;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

@Component
public class EmailSender implements MessageListener {
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void onMessage(Message message) {
        try {
            byte[] messageBody = message.getBody();
            Map<String,String> map = JSON.parseObject(messageBody, Map.class);
            String email = map.get("email");
            String subject = map.get("subject");
            String content = map.get("content");
//            MailUtil.sendMsg(email,subject,content); // 使用工具类发送邮件
            // 使用spring自带类发送邮件
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom("lei815029465@163.com");
            helper.setTo(email);
            helper.setSubject(subject);
//            helper.addAttachment("31.jpg",new File("C:\\Users\\Yimoer\\Desktop\\31.jpg"));
            helper.setText(content);
//            helper.addInline("myCid",new File("C:\\Users\\Yimoer\\Desktop\\31.jpg"));

            javaMailSender.send(mimeMessage);
//            System.out.println(email + "的邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
